package com.example.servlet.response;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

/**
 * @program: sms
 * @description:
 * @author: zhanghz001
 * @create: 2020-11-01 19:48
 **/
@WebServlet("/response3")
public class ResponseDemo3 extends HttpServlet {

    private static final Logger logger = LoggerFactory.getLogger(ResponseDemo3.class);

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        doGet(req, resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int height = 35;
        int width = 200;
//创建内存图像
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        //画笔就一根
        Graphics g = image.getGraphics();

        //
        g.setColor(Color.BLUE);

        g.drawLine(0, 0, width, height);

        // g.setColor();

        g.setColor(Color.GRAY);

        g.fillRect(0, 0, width, height);

        //颜色
        g.setColor(Color.WHITE);

        //
        Random r = new Random();
        //拿随机数对象
        for (int i = 0; i < 10; i++) {
            g.drawLine(r.nextInt(width), r.nextInt(height), r.nextInt(width), r.nextInt(height));
        }
        //设置颜色
        g.setColor(Color.RED);

        //改变字体大小
        Font font = new Font("宋体", Font.BOLD, 30);
        g.setFont(font);

        //画验证码
        int x = 35;
        for (int i = 0; i < 4; i++) {
            g.drawString(String.valueOf(r.nextInt(10)), x, 25);
            x += 35;
        }
        ImageIO.write(image, "jpg", resp.getOutputStream());
    }

}
